<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item>
        <el-date-picker type="datetimerange"
                        :default-time="['00:00:00', '23:59:59']"
                        v-model="queryParams.myCreateTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="-" start-placeholder="创建开始日期"
                        end-placeholder="创建结束日期" clearable>
        </el-date-picker>
      </el-form-item>

      <el-form-item prop="createBy">
        <el-select ref="receiveSelect"
                   v-model="queryParams.createBy"
                   filterable reserve-keyword
                   collapse-tags
                   placeholder="创建人"
                   clearable>
          <el-option
            v-for="item in sysUserList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option label="待处理" value="1"/>
          <el-option label="处理中" value="2"/>
          <el-option label="待审核" value="3"/>
          <el-option label="已过审" value="4"/>
          <el-option label="已完结" value="5"/>
          <el-option label="已关闭" value="6"/>
        </el-select>
      </el-form-item>

      <el-form-item prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择客诉来源" clearable>
          <el-option label="微信" value="1"/>
          <el-option label="抖音飞鸽" value="2"/>
          <el-option label="内部投诉热线" value="3"/>
          <el-option label="运营商投诉热线" value="4"/>
          <el-option label="国家职能监管部门" value="5"/>
        </el-select>
      </el-form-item>

      <el-form-item prop="emergency">
        <el-select v-model="queryParams.emergency" placeholder="请选择紧急程度" clearable>
          <el-option label="正常" value="1"/>
          <el-option label="紧急" value="2"/>
        </el-select>
      </el-form-item>

      <el-form-item prop="synthesize">
        <el-input
          v-model="queryParams.synthesize"
          placeholder="标题内容/订单编码/工单号/描述内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="ksOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="工单号" align="center" prop="ksId"/>
      <el-table-column label="标题" align="center" prop="title">
        <template #default="{row}">
          <span :title="row.content">
              <el-link type="primary" :underline="false" @click="goDetail(row)">{{ row.title }}</el-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="客诉来源" align="center" prop="source">
        <template #default="{row}">
          {{ sourceMap[row.source] }}
        </template>
      </el-table-column>
      <el-table-column label="客诉类型" align="center" prop="ksType">
        <template #default="{row}">
          {{ ksTypeMap[row.ksType] }}
        </template>
      </el-table-column>
      <el-table-column label="紧急情况" align="center" prop="emergency">
        <template #default="{row}">
          {{ emergencyMap[row.emergency] }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template #default="{row}">
          <span :style="{ color: getKsTagClass(row.state) }">
          {{ stateMap[row.state] }}
            </span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="latestReplyTime"/>
      <el-table-column label="处理时长" align="center" prop="handleTime">
        <template #default="{row}">
          <i class="el-icon-alarm-clock">
            {{ row.handleTime }}
          </i>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--     添加或修改客诉工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编码" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单id" disabled/>
        </el-form-item>


        <el-form-item label="工单号" prop="ksId">
          <el-input v-model="form.ksId" placeholder="请输入工单号" disabled/>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="form.state" placeholder="请输入1待处理2处理中3待审核4已完结5已关闭"/>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="问题描述" prop="content">
          <el-input v-model="form.content" placeholder="请输入问题描述"/>
        </el-form-item>
        <el-form-item label="来源:1微信2抖音飞鸽3内部投诉热线4运营商投诉热线5国家职能监管部门" prop="source">
          <el-input v-model="form.source"
                    placeholder="请输入来源:1微信2抖音飞鸽3内部投诉热线4运营商投诉热线5国家职能监管部门"/>
        </el-form-item>
        <el-form-item label="1正常2紧急" prop="emergency">
          <el-input v-model="form.emergency" placeholder="请输入1正常2紧急"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--客诉上传录音-->
    <el-dialog
      title="客诉上传录音"
      :visible.sync="ks.audio.open"
      width="400px"
      append-to-body
      :close-on-click-modal="!ks.audio.isUploading"
      :show-close="!ks.audio.isUploading"
    >
      <el-upload
        action="#"
        ref="audio"
        :limit="5"
        accept=".wav,.mp3,.m4a"
        :headers="ks.audio.headers"
        :disabled="ks.audio.isUploading"
        :on-exceed="audioExceed"
        :on-change="ksAudioFileChange"
        :before-upload="audioBeforeUpload"
        :auto-upload="false"
        drag
        :file-list="ks.audio.uploadFiles"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入mp3/wav/m4a格式文件,每个小于5M,最多3段录音</span>
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitKsAudioForm" :loading="ks.audio.isUploading"
                   :disabled="ks.audio.isUploading">
          {{ ks.audio.isUploading ? '上传中...' : '确 定' }}
        </el-button>
        <el-button @click="closeKsAudioUploadPage" :disabled="ks.audio.isUploading">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="ksOrder.titleAndTime" :visible.sync="ksOrderDetailVisible" width="60%"
               :close="ksOrderClose">
      <template #title>
        <span v-html="formatTitle"/>

      </template>

      <div style="display: flex;justify-content: space-between;align-items: flex-start; margin-bottom: 14px">
        <div style="width: 66%">
          <el-steps :active="Number(ks.active)" finish-status="success" active-color="#999">
            <el-step v-for="item in ks.stepsTitleList" :title="item" :key="item"></el-step>
          </el-steps>
        </div>

        <div style="width: 16%;display: flex;justify-content: flex-end;">
          <el-button type="success" size="small" @click="flushKsOrderLog">刷新消息
          </el-button>
          <el-button type="primary" size="small" v-show="ksOrder.state == 2" @click="ksAddAuditPermise">方案审核
          </el-button>
          <el-button type="primary" size="small" @click="ksWanJieOrderPremise"
                     v-show="(ksOrder.state == 3 && !ksOrder.auditUser) || ksOrder.state == 4">完结工单
          </el-button>
          <el-button type="primary" size="small" @click="ksCloseOrderPremise" v-show="ksOrder.state == 2">关闭工单
          </el-button>
        </div>
      </div>


      <div style="display: flex;justify-content: space-between;" class="dialog-content-container">
        <div style="width: 26%">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>工单信息</span>
            </div>
            <div class="myTitle">
              发起人员
            </div>
            <div>
              {{ ksOrder.createBy }}
            </div>
            <div class="myTitle">
              客诉时间
            </div>
            <div>
              {{ ksOrder.createTime }}
            </div>
            <div class="myTitle">
              客诉来源
            </div>
            <div>
              {{ sourceMap[ksOrder.source] }}
            </div>
            <div class="myTitle">
              客诉类型
            </div>
            <div>
              {{ ksTypeMap[ksOrder.ksType] }}
            </div>
            <div class="myTitle">
              紧急程度
            </div>
            <div>
              {{ emergencyMap[ksOrder.emergency] }}
            </div>

            <div class="myTitle">
              工单编号
            </div>
            <div>
              {{ ksOrder.ksId }}
            </div>
            <div class="myTitle">
              订单编号
            </div>
            <div>
              {{ ksOrder.orderId }}
            </div>

            <div class="myTitle">
              客户姓名
            </div>
            <div>
              {{ ksOrder.customName }}
            </div>

            <div class="myTitle">
              证件号码
            </div>
            <div>
              {{ ksOrder.customNumber }}
            </div>
            <div class="myTitle">
              客户年龄
            </div>
            <div>
              {{ ksOrder.customNumberAge }}
            </div>
            <div class="myTitle">
              订单号码
            </div>
            <div>
              {{ ksOrder.telNumber }}
            </div>
            <div class="myTitle">
              联系电话
            </div>
            <div>
              {{ ksOrder.customTel }}
            </div>
            <div class="myTitle">
              联系地址
            </div>
            <div>
              {{ ksOrder.customAddress }}
            </div>
            <div class="myTitle">
              渠道信息
            </div>
            <div>

              {{ ksOrder.channelName }}/{{ ksOrder.channelCode }}
            </div>

            <div class="myTitle">
              渠管信息
            </div>
            <div>
              {{ ksOrder.contactUser }}
            </div>
            <div class="myTitle">
              描述信息
            </div>
            <div>
              {{ ksOrder.content }}
            </div>
          </el-card>
        </div>
        <div style="width: 72%;">
          <el-card class="box-card">
            <el-timeline>
              <el-timeline-item timestamp="发送消息" placement="top">
                <el-card :body-style="{padding: '10px' }">
                  <el-form :model="ksOrderReplyForm">

                    <el-tag size="mini" type="info" v-show="ksOrderReplyForm.referenceVisible" closable
                            @close="ksFormClose()">
                      {{ ksOrderReplyForm.creteTime }} {{ ksOrderReplyForm.replyNickName }} :123
                      <span style="color:#409EFF">
                          {{ ksOrderReplyForm.referenceContent }}
                      </span>
                    </el-tag>
                    <div style="display: flex; justify-content: space-between;margin-bottom: 2px">
                      <el-input type="textarea" v-model="ksOrderReplyForm.replyContent"
                                :placeholder="ks.attachmentTxt"></el-input>
                      <el-button type="primary" style="margin-left: 2px" size="mini" @click="ksOrderReplyFormSubmit">发送
                      </el-button>
                    </div>
                    <div>
                      <el-tag icon="el-icon-refresh" style="margin-left: 1px;cursor: pointer"
                              @click="importKsOrderImage()" size="mini" type="primary">
                        <i class="el-icon-s-platform"></i>上传图片
                      </el-tag>
                      <el-tag style="margin-left: 1px;cursor: pointer"
                              @click="ksImportAudio()" size="mini" type="primary">
                        <i class="el-icon-s-platform"></i>上传录音
                      </el-tag>
                      <el-tag style="margin-left: 1px;cursor: pointer"
                              @click="generateQR()" size="mini" type="primary"><i class="el-icon-full-screen"></i>扫码上传
                      </el-tag>
                    </div>
                    <canvas ref="qrcodeCanvas" style="width: 0px; height: 0px;"></canvas>
                  </el-form>
                </el-card>
              </el-timeline-item>
              <el-timeline-item
                :timestamp="item.createTime+' '+item.roleName+'-'+item.nickName"
                placement="top"
                v-for="item in ksOrderReplayLogs"
                :key="item.id">
                <el-card :body-style="{padding: '10px' }" :class="{'gray-bg': !contentCheck(item.replyContent)}">
                  <div>
                    <el-link icon="el-icon-s-comment" type="info" v-show="item.referenceContent" disabled>
                      {{ item.referenceTime }} {{ item.referenceNickName }} : {{ item.referenceContent }}
                    </el-link>
                  </div>
                  <div>
                    {{ item.replyContent }}
                  </div>
                  <div style="display: flex;justify-content: space-between;margin-top: 2px">
                    <div style=" display: flex;justify-content: flex-start">
                      <el-tag style="margin-left: 1px;cursor: pointer" v-show="item.imageKsAttachmentList"
                              @click="ksShowAttachmentByImages(item.imageKsAttachmentList)" size="mini" type="success">
                        <i class="el-icon-picture"></i>查看图片
                      </el-tag>
                      <el-tag style="margin-left: 1px;cursor: pointer" v-show="item.audioKsAttachmentList"
                              @click="ksShowAttachmentByAudio(item.audioKsAttachmentList)" size="mini" type="success"><i
                        class="el-icon-s-comment"></i>回放录音
                      </el-tag>
                    </div>
                    <el-tag size="mini" v-if="contentCheck(item.replyContent)" type="info"
                            @click="preReferenceContent(item)" effect="plain">回复
                    </el-tag>
                  </div>
                </el-card>
              </el-timeline-item>

            </el-timeline>
          </el-card>
        </div>
      </div>
    </el-dialog>


    <!--    客诉上传图片-->
    <el-dialog
      title="客诉上传图片"
      :visible.sync="ks.image.open"
      width="400px"
      append-to-body
      :close-on-click-modal="!ks.image.isUploading" :show-close="!ks.image.isUploading">
      <el-upload
        action="#"
        ref="ksImage"
        :limit="5"
        :on-exceed="imageExceed"
        accept=".jpg, .png"
        :headers="ks.image.headers"
        :disabled="ks.image.isUploading"
        :on-change="ksImageFileChange"
        :before-upload="imageBeforeUpload"
        :auto-upload="false"
        list-type="picture"
        drag
        :file-list="ks.image.uploadFiles"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入jpg, png格式文件,最多5张图片。</span>
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitKsImageForm" :loading="ks.image.isUploading"
                   :disabled="ks.image.isUploading">
          {{ ks.image.isUploading ? '上传中...' : '确 定' }}
        </el-button>
        <el-button @click="closeKsImageUploadPage" :disabled="ks.image.isUploading">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="this.ksOrder.orderId+'客诉图片列表'" :visible.sync="ksShowAttachmentImagesDiagLogVisible"
               width="800px">
      <div class="image-grid">
        <div v-for="item in ksAttachmentImagesList" :key="item.id">
          <el-card :body-style="{ padding: '2px' }" shadow="hover">
            <el-image
              :preview-src-list="[item.fullPath]"
              :src="item.fullPath"
              lazy
              style="width: 100%; height: 180px; object-fit: contain;"
            ></el-image>
            <el-tag type="danger" @click="ksDeleteAttachment(item)" style="width: 100%;cursor: pointer">
              删除
            </el-tag>
          </el-card>
        </div>
      </div>
    </el-dialog>


    <el-dialog :title="this.ksOrder.orderId+'客诉录音列表'" :visible.sync="ksShowAttachmentAudioDiagLogVisible"
               width="800px">
      <div>
        <div v-for="(audio, index) in audioKsAttachmentList" :key="index" class="audio-item">
          <p>{{ audio.objectPath }}</p>
          <div style="display:flex; align-items: center">
            <audio controls :src="audio.fullPath"></audio>
            <el-tag size="medium" type="danger" @click="ksDeleteAttachment(audio)"
                    style="margin-left:4px;cursor: pointer">
              删除
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="输入调关闭工单理由,并确认" :visible.sync="ks.closeFormVisible" width="400px">
      <el-form :model="ks.closeForm" @submit.native.prevent="enterSubmit">
        <el-form-item>
          <el-input type="textarea" v-model="ks.closeForm.content" placeholder="请输入.."></el-input>
        </el-form-item>
      </el-form>
      <div class="hjfBottomFoot">
        <el-button size="small" @click="ks.closeFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="ksCloseFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="输入审核工单理由,并确认" :visible.sync="ks.auditFormVisible" width="400px">
      <el-form :model="ks.auditForm" @submit.native.prevent="enterSubmit">
        <el-form-item>
          <el-select v-model="ks.auditForm.auditUserId" placeholder="请选择审核人" style="width: 100%" clearable>
            <el-option v-for="item in ks.auditUserIds" :key="item.userId" :label="item.nickName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input type="textarea" v-model="ks.auditForm.content" placeholder="请输入.."></el-input>
        </el-form-item>
      </el-form>
      <div class="hjfBottomFoot">
        <el-button size="small" @click="ks.auditFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="ksAuditFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="输入调完结工单理由,并确认" :visible.sync="ks.wanJieFormVisible" width="400px">
      <el-form :model="ks.wanJieForm" @submit.native.prevent="enterSubmit">
        <el-form-item>
          <el-input type="textarea" v-model="ks.wanJieForm.content" placeholder="请输入.."></el-input>
        </el-form-item>
      </el-form>
      <div class="hjfBottomFoot">
        <el-button size="small" @click="ks.wanJieFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="ksWanJieFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addKsOrder,
  delKsOrder,
  getKsOrder,
  listKsOrder,
  listKsOrderReplyLog,
  selectRxOrderBySerial,
  selectUsersByIds,
  updateKsOrder,
} from "@/api/hmk/ksOrder";
import {getToken} from "@/utils/auth";
import {addKsOrderReplyLogAndUpload, getKsTempUrl, ksAddAuditUserId, ksDeleteAttachment} from "@/api/hmk/order";
import {enterSubmit, getKsTagClass} from "@/utils/hjf-common";
import {getSimpleUserList} from "@/api/system/user";
import QRCode from "qrcode";


export default {

  name: "KsOrder",
  data() {
    return {
      sysUserList: [],
      ksAttachmentImagesList: [],
      audioKsAttachmentList: [],
      ksShowAttachmentImagesDiagLogVisible: false,
      ksShowAttachmentAudioDiagLogVisible: false,
      ks: {
        attachmentTxt: null,
        guanBi: ["分配专员", "开始处理", "关闭工单"],
        zhengChang: ["分配专员", "开始处理", "方案审核", "执行解决", "完结工单"],
        stepsTitleList: this.zhengChang,
        wanJieFormVisible: false,
        wanJieForm: {
          content: null,
        },
        auditForm: {
          auditUserId: null,
          content: null,
        },
        auditUserIds: [],
        auditFormVisible: false,
        closeFormVisible: false,
        closeForm: {
          content: null,
        },
        active: 1,
        image: {
          imageResUrls: [],
          uploadFiles: [],
          open: false,
          isUploading: false,
          headers: {Authorization: "Bearer " + getToken()}
        },

        audio: {
          audioResUrls: [],
          uploadFiles: [],
          open: false,
          isUploading: false,
          headers: {Authorization: "Bearer " + getToken()}
        },
      },
      ksOrderReplayLogs: [],
      ksOrderReplyForm: {
        referenceVisible: false,
        replyContent: null,
        referenceContent: null,
        referenceId: null,
      },
      ksOrder: {
        id: null,
        orderId: null,
        channelName: null,
        channelCode: null,
        contactUser: null,
        title: null,
        customName: null,
        customNumber: null,
        customAddress: null,
        customTel: null,
        customNumberAge: null,
        createBy: null,
        titleAndTime: null,
      },
      ksOrderDetailVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客诉工单表格数据
      ksOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        ksId: null,
        state: null,
        title: null,
        content: null,
        source: null,
        emergency: null,
        ksType: null,
        myCreateTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          {required: true, message: "订单id不能为空", trigger: "blur"}
        ],
        ksId: [
          {required: true, message: "工单号不能为空", trigger: "blur"}
        ],
        state: [
          {required: true, message: "1待处理2处理中3待审核4已完结5已关闭不能为空", trigger: "blur"}
        ],
        title: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        content: [
          {required: true, message: "问题描述不能为空", trigger: "blur"}
        ],
        source: [
          {
            required: true,
            message: "来源:1微信2抖音飞鸽3内部投诉热线4运营商投诉热线5国家职能监管部门不能为空",
            trigger: "blur"
          }
        ],
        emergency: [
          {required: true, message: "1正常2紧急不能为空", trigger: "blur"}
        ],
        ksType: [
          {required: true, message: "客诉类型:1赠款赔偿2变更套餐3装机移机4取消协议5拆机销户不能为空", trigger: "change"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
      }
    };
  },
  computed: {
    formatTitle() {
      if (!this.ksOrder.titleAndTime) return '';
      return this.ksOrder.titleAndTime.replace(/ /g, '<i class="el-icon-alarm-clock"></i>')
    },
    ksTypeMap() {
      return {
        1: "赠款赔偿",
        2: "变更套餐",
        3: "装机移机",
        4: "取消协议",
        5: "拆机销户",
      }
    },
    emergencyMap() {
      return {
        1: "正常",
        2: "紧急",
      }
    },
    sourceMap() {
      return {
        1: "微信",
        2: "抖音飞鸽",
        3: "内部投诉热线",
        4: "运营商投诉热线",
        5: "国家职能监管部门",
      }
    },
    stateMap() {
      return {
        1: "待处理",
        2: "处理中",
        3: "待审核",
        4: "已过审",
        5: "已完结",
        6: "已关闭",
      }
    },
  },
  created() {
    getSimpleUserList().then(response => {
      this.sysUserList = response.data;
      sessionStorage.setItem('sysUserList', JSON.stringify(this.sysUserList));
    });
    this.getList();
  },
  methods: {
    generateQR() {
      const canvas = this.$refs['qrcodeCanvas'];

      // let fullUrl = "http://192.168.0.100/public/ks-qrcode-redirect" + "?ksId=" + this.ksOrder.id + '&orderId=' + this.ksOrder.orderId
      let fullUrl = "http://hmk.haomaku.vip/public/ks-qrcode-redirect" + "?ksId=" + this.ksOrder.id + '&orderId=' + this.ksOrder.orderId
      if (this.ksOrderReplyForm.referenceId) {
        fullUrl += '&referenceId=' + this.ksOrderReplyForm.referenceId
      }
      if (this.ksOrderReplyForm.referenceContent) {
        fullUrl += '&referenceContent=' + this.ksOrderReplyForm.referenceContent
      }

      this.generateFinalQR(canvas, fullUrl);
    },

    generateFinalQR(canvas, fullUrl) {
      QRCode.toCanvas(canvas, fullUrl, {
        width: 200,  // 建议最小200px
        margin: 2,
        color: {
          dark: '#000000',
          light: '#ffffff'
        }
      });
    },
    getKsTagClass,
    ksAuditFormConfirm() {
      if (!this.ks.auditForm.content) {
        return this.$modal.msgError('审批消息必填!')
      }
      this.loading = true;
      ksAddAuditUserId({
        "auditUserId": this.ks.auditForm.auditUserId, "replyContent":
        this.ks.auditForm.content, "orderId": this.ksOrder.orderId,
        "ksId": this.ksOrder.id,
      }).then(res => {
        this.flushKsOrderLog()
      })
      this.ks.auditFormVisible = false;
      this.loading = false;
    },
    ksWanJieFormConfirm() {
      if (!this.ks.wanJieForm.content) {
        return this.$modal.msgError('完结消息必填!')
      }
      const formData = new FormData();
      formData.append("replyContent", this.ks.wanJieForm.content);


      if (this.ksOrder.orderId) {
        formData.append("orderId", this.ksOrder.orderId);
      }
      if (this.ksOrder.id) {
        formData.append("ksId", this.ksOrder.id);
      }
      formData.append("state", 5);

      this.loading = true;
      addKsOrderReplyLogAndUpload(formData).then(res => {
        this.flushKsOrderLog()
      })
      this.ks.wanJieFormVisible = false;
      this.loading = false;
    },

    ksCloseFormConfirm() {
      if (!this.ks.closeForm.content) {
        return this.$modal.msgError('完结消息必填!')
      }
      const formData = new FormData();
      formData.append("replyContent", this.ks.closeForm.content);
      if (this.ksOrder.orderId) {
        formData.append("orderId", this.ksOrder.orderId);
      }
      if (this.ksOrder.id) {
        formData.append("ksId", this.ksOrder.id);
      }
      formData.append("state", 6);

      this.loading = true;
      addKsOrderReplyLogAndUpload(formData).then(res => {
        this.flushKsOrderLog()
      })
      this.ks.closeFormVisible = false;
      this.loading = false;
    },
    enterSubmit,
    ksDeleteAttachment(item) {
      ksDeleteAttachment({'id': item.id}).then(res => {
        this.$modal.msgSuccess("删除订单附件成功!")
        listKsOrderReplyLog({'ksId': this.ksOrder.id}).then(res => {
          this.ksOrderReplayLogs = res.rows;
        })
        this.ksShowAttachmentImagesDiagLogVisible = false
        this.ksShowAttachmentAudioDiagLogVisible = false
      })
    },
    ksShowAttachmentByImages(ksAttachments) {
      getKsTempUrl(ksAttachments).then(res => {
        this.ksAttachmentImagesList = res.data;
        this.ksShowAttachmentImagesDiagLogVisible = true;
      })
    },

    ksShowAttachmentByAudio(ksAttachments) {
      getKsTempUrl(ksAttachments).then(res => {
        this.audioKsAttachmentList = res.data;
        this.ksShowAttachmentAudioDiagLogVisible = true;
      })
    },
    ksImportAudio() {
      this.ks.audio.uploadFiles = [];
      this.ks.audio.audioResUrls = [];
      this.userId = this.$store.state.user.id;
      if (this.ks.attachmentTxt) {
        if (this.ks.attachmentTxt.toString().indexOf('录音') > 0) {
          this.ks.attachmentTxt = null;
        }
      }
      this.ks.audio.open = true;
    },

    importKsOrderImage() {
      this.ks.imageResUrls = [];
      this.ks.image.uploadFiles = [];
      this.userId = this.$store.state.user.id
      if (this.ks.attachmentTxt) {
        //
        // if(this.ks.attachmentTxt.toString().indexOf('图片') > 0 && this.ks.attachmentTxt.toString().indexOf('录音') > 0 ){
        //   this.ks.attachmentTxt = null;
        // }
        if (this.ks.attachmentTxt.toString().indexOf('图片') > 0) {
          this.ks.attachmentTxt = null;
        }
      }
      this.ks.image.open = true;
    },


    imageBeforeUpload(file) {
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        return this.$message.error('图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        return this.$message.error('图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    ksFormClose() {
      this.ksOrderReplyForm.referenceVisible = false;
      this.ksOrderReplyForm.referenceContent = null;
      this.ksOrderReplyForm.referenceId = null;
    },
    ksImageFileChange(file, fileList) {
      this.ks.image.uploadFiles = fileList;
    },
    flushKsOrderLog() {
      this.ks.image.uploadFiles = [];
      this.ks.audio.uploadFiles = [];
      this.ksFormClose();
      listKsOrderReplyLog({'ksId': this.ksOrder.id}).then(res => {
        this.ksOrderReplayLogs = res.rows;
        if (this.ksOrderReplayLogs.length > 0) {

          if (this.ksOrderReplayLogs[0].state) {
            this.ksOrder.state = this.ksOrderReplayLogs[0].state
            this.ks.active = this.ksOrder.state;
            if (this.ksOrder.state == 6) {
              this.ks.active = 3;
              this.ks.stepsTitleList = this.ks.guanBi;
            } else {
              this.ks.stepsTitleList = this.ks.zhengChang;
            }
          }
        } else {
          this.ks.stepsTitleList = this.ks.zhengChang;
          this.ks.active = 1;
          this.ksOrder.state = 1;
        }
        this.ksFormClose();
      })
    },
    contentCheck(content) {
      const keywords = ["创建客诉工单", "分配专员处理", "关闭客诉工单", "完结客诉工单", "添加处理方案", "添加处理方案，等待审核"];
      return !keywords.some(keyword => content.includes(keyword));
    },
    ksOrderClose() {
      this.ksOrderDetailVisible = false;
      this.getList();
    },
    ksCloseOrderPremise() {
      this.ks.closeForm.content = null;
      this.ks.closeFormVisible = true;
      this.ks.stepsTitleList = this.ks.guanBi;
    },
    ksWanJieOrderPremise() {
      this.ks.wanJieForm.content = null;
      this.ks.wanJieFormVisible = true;
    },
    ksAddAuditPermise() {
      this.ks.auditUserId = null;
      selectUsersByIds().then(res => {
        this.ks.auditUserIds = res.data;
      })
      this.ks.auditForm.content = null;
      this.ks.auditFormVisible = true;
    },
    closeKsImageUploadPage() {
      this.ks.image.uploadFiles = [];
      this.ks.image.open = false;
    },
    closeKsAudioUploadPage() {
      this.ks.audio.uploadFiles = [];
      this.ks.audio.open = false;
    },
    ksAudioFileChange(file, fileList) {
      this.ks.audio.uploadFiles = fileList;
    },
    submitKsAudioForm() {
      if (this.ks.audio.uploadFiles.length === 0) {
        this.$message.warning("请先选择文件");
        return;
      }
      if (this.ks.attachmentTxt) {
        this.ks.attachmentTxt += "[已选录音" + this.ks.audio.uploadFiles.length + "段]";
      } else {
        this.ks.attachmentTxt = "[已选录音" + this.ks.audio.uploadFiles.length + "段]";
      }

      if ((this.ks.audio.uploadFiles.length) > 3) {
        this.$message.warning("你本次上传的总数大于3,请删除一些");
        return;
      }
      this.$message.success("请输入跟进消息并点击发送!");
      this.ks.audio.open = false;
    },

    submitKsImageForm() {
      if (this.ks.image.uploadFiles.length === 0) {
        this.$message.warning("请先选择文件");
        return;
      }

      if (this.ks.attachmentTxt) {
        this.ks.attachmentTxt += "[已选图片" + this.ks.image.uploadFiles.length + "张]";
      } else {
        this.ks.attachmentTxt = "[已选图片" + this.ks.image.uploadFiles.length + "张]";
      }


      if ((this.ks.image.uploadFiles.length) > 5) {
        this.$message.warning("你本次上传的总数大于5,请删除一些");
        return;
      }
      this.$message.success("请输入跟进消息并点击发送!");
      this.ks.image.open = false;
    },

    audioExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    imageExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    audioBeforeUpload(file) {
      const isAudio = ['audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/x-m4a'].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isAudio) {
        return this.$message.error('音频只能是mp3/wav/m4a 格式!');

      }
      if (!isLt5M) {
        return this.$message.error('音频大小不能超过 5MB!');
      }
      return isAudio && isLt5M;
    },
    handleClose() {
      this.ksOrderReplyForm.referenceVisible = false;
      this.ksOrderReplyForm.referenceContent = null;
      this.ksOrderReplyForm.referenceId = null;
    },
    preReferenceContent(item) {
      this.ksOrderReplyForm.referenceVisible = true;
      this.ksOrderReplyForm.referenceContent = item.replyContent;
      this.ksOrderReplyForm.replyNickName = item.nickName;
      this.ksOrderReplyForm.creteTime = item.createTime;
      this.ksOrderReplyForm.referenceId = item.id;
    },
    ksOrderReplyFormSubmit() {
      const formData = new FormData();

      this.ks.image.uploadFiles.forEach(file => {
        formData.append("files", file.raw);
      });
      this.ks.audio.uploadFiles.forEach(file => {
        formData.append("audioFiles", file.raw);
      });

      if (this.ksOrderReplyForm.replyContent) {
        formData.append("replyContent", this.ksOrderReplyForm.replyContent);
      } else {
        this.$modal.msgError('回复消息必填!')
        return
      }
      if (this.ksOrderReplyForm.referenceId) {
        formData.append("referenceId", this.ksOrderReplyForm.referenceId);
      }
      if (this.ksOrderReplyForm.referenceContent) {
        formData.append("referenceContent", this.ksOrderReplyForm.referenceContent);
      }
      if (this.ksOrder.orderId) {
        formData.append("orderId", this.ksOrder.orderId);
      }
      if (this.ksOrder.id) {
        formData.append("ksId", this.ksOrder.id);
      }

      this.loading = true;
      addKsOrderReplyLogAndUpload(formData).then(res => {
        this.ksOrderReplyForm.replyContent = null;
        this.flushKsOrderLog()

      })
      this.ks.image.open = false;
      this.loading = false;
      this.ks.attachmentTxt = null;
    },
    // goDetail2(row) {
    //   this.$router.push({
    //     path: '/order/order',
    //   });
    //   this.$store.commit('SET_KS_ORDER_ID', row);
    //   this.$store.commit('SET_ksOrderDetailVisible');
    // },
    goDetail(row) {
      this.ksOrder = {...row};
      this.ksOrderDetailVisible = true;
      this.ksOrderReplyForm.referenceContent = null;
      this.ksOrderReplyForm.referenceVisible = false;
      this.audioKsAttachmentList = [];
      this.ksAttachmentImagesList = [];
      this.ksOrderReplyForm.replyContent = null;
      this.ks.image.uploadFiles = [];
      this.ks.audio.uploadFiles = [];
      this.loading = true;
      this.flushKsOrderLog();
      selectRxOrderBySerial(this.ksOrder.orderId).then(res => {
        this.ksOrder = {
          ...this.ksOrder,
          customName: res.data.customName,
          customNumber: res.data.customNumber,
          customAddress: res.data.shengId + res.data.cityId + res.data.areaId + res.data.streetId + res.data.realAddress,
          customTel: res.data.customTel,
          telNumber: res.data.telNumber,
          customNumberAge: res.data.customNumberAge,
          channelName: res.data.channelName,
          channelCode: res.data.channelCode,
          contactUser: res.data.contactUser,
        }
      })
      this.loading = false;
    },
    /** 查询客诉工单列表 */
    getList() {
      this.loading = true;
      listKsOrder(this.queryParams).then(response => {
        this.ksOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        ksId: null,
        state: null,
        title: null,
        content: null,
        source: null,
        emergency: null,
        ksType: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.myCreateTime = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客诉工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getKsOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客诉工单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateKsOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addKsOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客诉工单编号为"' + ids + '"的数据项？').then(function () {
        return delKsOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hmk/ksOrder/export', {
        ...this.queryParams
      }, `ksOrder_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>

.myTitle {
  color: #c8c8c9;
  margin-top: 6px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
}

.hjfBottomFoot {
  display: flex;
  justify-content: end;
}

.gray-bg {
  background-color: #f0f0f0; /* 灰色背景 */
}


.dialog-content-container {
  max-height: calc(80vh - 170px); /* 减去标题和按钮高度 */
  overflow-y: auto;
}

</style>
